package top.yoahh.system.service.impl;

import top.yoahh.system.entity.SysMenu;
import top.yoahh.system.mapper.SysMenuMapper;
import top.yoahh.system.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import top.yoahh.common.Result;
import top.yoahh.system.query.SysMenuQueryInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 系统资源-菜单 服务实现类
 * </p>
 *
 * @author hjx
 * @since 2022-05-19
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Override
    public PageInfo<SysMenu> queryPage(SysMenuQueryInfo queryInfo) {
        PageHelper.startPage(queryInfo.getPageNum(), queryInfo.getPageSize());
        List<SysMenu> userList = baseMapper.queryList(queryInfo);
        return new PageInfo<>(userList);
    }

    @Override
    public Result deleteBatch(List<String> ids) {
        baseMapper.deleteBatchIds(ids);
        return Result.ok();
    }

    @Override
    public Result delete(String id) {
        baseMapper.deleteById(id);
        return Result.ok();
    }

    @Override
    public Result queryMenuTree(SysMenuQueryInfo queryInfo) {
        // 查询所有的菜单集合
        List<SysMenu> menuList = baseMapper.queryList(queryInfo);
        ArrayList<SysMenu> rootMenuList = new ArrayList<>();
        for (SysMenu menu : menuList) {
            if ("#".equals(menu.getParentId())) {
                rootMenuList.add(menu);
                getChild(menu, menuList);
            }
        }
        return new Result(rootMenuList);
    }

    /**
     * 递归获取，子集菜单
     *
     * @param menu 根菜单
     * @param list 所有菜单集合
     */
    private void getChild(SysMenu menu, List<SysMenu> list) {
        ArrayList<SysMenu> childrenList = new ArrayList<>();
        menu.setChildren(childrenList);
        for (SysMenu child : list) {
            if (menu.getId().equals(child.getParentId())) {
                childrenList.add(child);
                getChild(child, list);
            }
        }
    }
}
